'use client'

import React, { createContext, useContext, useEffect, ReactNode, Suspense } from 'react'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
import { useCurrentStudent, useAuthActions } from '@/hooks/useAuth'
import { User } from '@/types/user'

interface AuthContextType {
  student: User | null
  loading: boolean
  error: string | null
  login: (token: string) => void
  logout: () => void
  isAuthenticated: boolean
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

function AuthClientProviderInner({ children }: { children: ReactNode }) {
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()

  // 不需要认证的页面
  const publicPaths = ['/login']

  // 检查是否正在处理企业微信免登录
  const isWeChatAutoLogin = searchParams?.get('token') && searchParams?.get('user')

  // 使用 React Query hooks
  const { data: student, isLoading: loading, error: queryError } = useCurrentStudent()
  const { login: handleLogin, logout: handleLogout } = useAuthActions()

  // 处理错误信息
  const error = queryError ? (queryError as any)?.message || '获取用户信息失败' : null

  useEffect(() => {
    // 如果是公开页面，不需要检查认证
    if (publicPaths.includes(pathname || '')) {
      return
    }

    // 如果正在处理企业微信免登录，暂停认证检查
    if (isWeChatAutoLogin) {
      console.log('检测到企业微信免登录参数，暂停认证检查')
      return
    }

    // 如果查询出错且是认证相关错误，跳转到登录页
    if (queryError && !loading) {
      const errorMessage = (queryError as any)?.message || ''
      if (errorMessage.includes('未登录') || (queryError as any)?.status === 401) {
        localStorage.removeItem('token')
        router.push('/login')
      }
    }
  }, [pathname, queryError, loading, router, isWeChatAutoLogin])

  const value = {
    student: student || null,
    loading,
    error,
    login: handleLogin,
    logout: handleLogout,
    isAuthenticated: !!student,
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

export function AuthClientProvider({ children }: { children: ReactNode }) {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
          <p className="text-gray-600">正在加载...</p>
        </div>
      </div>
    }>
      <AuthClientProviderInner>{children}</AuthClientProviderInner>
    </Suspense>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthClientProvider')
  }
  return context
}